﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kingdoms.Territories;
using WCell.Constants.GameObjects;
using WCell.Core.Initialization;
using WCell.RealmServer;
using WCell.RealmServer.Entities;
using WCell.RealmServer.GameObjects;
using WCell.RealmServer.Guilds;
using WCell.Core.Timers;

namespace Kingdoms
{
    public static class TerritoryMgr
    {
        public static Dictionary<int, Territory> TerritoryList = new Dictionary<int, Territory>();


        [Initialization(InitializationPass.Last, "Initializing Kingdom Territories...")]
        public static void Init()
        {
            #region regions
            ExampleTerritory example = new ExampleTerritory(); 
            TerritoryList.Add(example.Id, example);
            #endregion
            KingdomGuildMgr.Init();

            foreach (Territory territory in TerritoryList.Values)
            {
                territory.Template.Region.RegionInfo.Spawned += rgn => territory.Start();
            }
        }

        static void DoUpkeep()
        {
            foreach (Territory territory in TerritoryList.Values)
            {
                if (territory.Owner != null)
                {
                    var owner = KingdomGuildMgr.Guilds[territory.Owner.Id];
                    if (!(owner.GuildPoints - territory.CostPerUpkeep() < 0))
                    {
                        owner.GuildPoints -= territory.CostPerUpkeep();
                    }
                    else
                    {
                        territory.Reset();
                    }
                }
            }
        }

        public static void OnCapture(Guild captureguild, Territory territory, Guild PreviousOwnedBy)
        {
            if (!KingdomGuildMgr.Guilds.ContainsKey(captureguild.Id))
            {
                KingdomGuildMgr.AddGuild(captureguild);
            }
            if (PreviousOwnedBy != null)
            {
                var previous = KingdomGuildMgr.Guilds[PreviousOwnedBy.Id];
                previous.OwnedTerritories.Remove(territory);
            }
            var capturer = KingdomGuildMgr.Guilds[captureguild.Id];
            capturer.OwnedTerritories.Add(territory);
        }

        public static void OnReset(Territory t, Guild PreviousOwner)
        {
            if (PreviousOwner != null)
            {
                //do one message here
            }
            else
            {
                //could do some overall message crap here
            }
        }

    }
}
